﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Prism.DryIoc;
using Prism.Ioc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace LaserAutoTest.UI.Extensions
{
    public static class GlobalExceptionFilter
    {
        private static ILogger _logger;

        public static void CatchException(this IContainerRegistry containerRegistry)
        {
            _logger = containerRegistry.GetContainer().GetService<ILogger>();

            App.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;//处理在UI线程上未处理的异常
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;//处理在非UI线程上未处理的异常,当前域未处理异常
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;//处理在Task上未处理的异常
        }

        private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            AddLogError(e.Exception);
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;
            AddLogError(ex);
        }

        private static void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            AddLogError(e.Exception);
        }


        private static void AddLogError(Exception e)
        {
            _logger.LogError($"-------------------------------全局异常捕获开始-------------------------------");
            _logger.LogError($"{e.Message}");
            _logger.LogError($"{e.StackTrace}");
            _logger.LogError($"-------------------------------全局异常捕获结束-------------------------------");
        }
    }
}
